package com.longcai.controller.goods;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.longcai.bean.ApiResult;
import com.longcai.entity.homepage.GoodsClass;
import com.longcai.service.goods.GoodsClassService;
import com.longcai.util.OSSUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 商品类型 前端控制器
 * </p>
 *
 * @author LWK
 * @since 2019-03-20
 */
@Controller
@RequestMapping("/goodsClass")
public class GoodsClassController {
    @Autowired
    GoodsClassService bannerService;

    /**
     * description: 首页活动分类展示
     * author: LWK
     * time：2019年3月21日10点58分
     */
    @RequestMapping("/getHomepageClassList")
    @ResponseBody
    public List<GoodsClass> getHomepageClassList() {
        ApiResult<List<GoodsClass>> result = new ApiResult<List<GoodsClass>>();
        try {
            QueryWrapper<GoodsClass> queryWrapper = new QueryWrapper<GoodsClass>();
            queryWrapper.orderByAsc("type_sort");
            result.success();
            return bannerService.selectList(queryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode("-1");
            result.fail("查询失败：" + e.getMessage());
        }
        return null;
    }

    /**
     * 所有菜单
     *
     * @return
     */
    @GetMapping("/all")
    @ApiOperation(value = "所有菜单")
    @ResponseBody
    public JSONArray goodsClassAll() {
        QueryWrapper<GoodsClass> queryWrapper = new QueryWrapper<GoodsClass>();
        queryWrapper.in("type", "0", "1");
        List<GoodsClass> selectList = bannerService.selectList(queryWrapper);
        queryWrapper.orderByAsc("type_sort");
        JSONArray array = new JSONArray();
        setPermissionsTree("0", selectList, array);

        return array;
    }

    /**
     * 菜单树
     *
     * @param pId
     * @param permissionsAll
     * @param array
     */
    private void setPermissionsTree(String pId, List<GoodsClass> permissionsAll, JSONArray array) {
        permissionsAll.forEach(a -> {
            if ((pId.equals("0") && a.getPId() == null) || (a.getPId() != null && a.getPId().equals(pId))) {
                String string = JSONObject.toJSONString(a);
                JSONObject parent = (JSONObject) JSONObject.parse(string);
                array.add(parent);

                if (permissionsAll.stream().filter(p -> p.getPId() != null && p.getPId().equals(a.getId())).findAny() != null) {
                    JSONArray child = new JSONArray();
                    parent.put("child", child);
                    setPermissionsTree(a.getId(), permissionsAll, child);
                }
            }
        });
    }

  /**
     * 一级菜单
     *
     * @return
     */
    @GetMapping("typesId")
    @ResponseBody
    public String[] typeId(String typesId) {
        GoodsClass a = bannerService.selectById(typesId);
        if(a.getPId()==null || a.getPId()=="0" || a.getPId().equals("0")) {
            String [] b ={"0","typeId"};
            return b;
        }
        GoodsClass c = bannerService.selectById(a.getPId());
        if(c.getPId()==null || c.getPId()=="0" || c.getPId().equals("0")) {
            String [] b ={"0",a.getPId(),typesId};
            return b;
        }
        String[] b = {"0",c.getPId(),a.getPId(),typesId};
        return b;
    }

    /**
     * 新增
     *
     * @param request
     * @param banner
     * @return
     */
    @PostMapping(value = "saveClass")
    @ResponseBody
    public boolean save(HttpServletRequest request, MultipartFile banner) {
        GoodsClass goodsClass = new GoodsClass();
        goodsClass.setId(UUID.randomUUID().toString());
        goodsClass.setCreateTime(LocalDateTime.now());
        goodsClass.setName(request.getParameter("name"));
        goodsClass.setPId(request.getParameter("pid"));
        goodsClass.setType(request.getParameter("type"));
        goodsClass.setTypeDesc(request.getParameter("typeDesc"));
        goodsClass.setTypeStatus(request.getParameter("typeStatus"));
        goodsClass.setTypeSort(request.getParameter("typeSort"));
        //文档上传oss
        try {
            String fileName = banner.getOriginalFilename();
            String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream inputStream = banner.getInputStream();
            Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODSCLASS/");
            goodsClass.setBanner(uploadByInputStream.get("path").toString());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.bannerService.insert(goodsClass);
        return true;
    }


    /**
     * 根据id获取分类
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    @ApiOperation(value = "根据id获取分类")
    @ResponseBody
    public GoodsClass get(@PathVariable String id) {
        return this.bannerService.selectById(id);
    }


    /**
     * 修改分类
     *
     * @param request
     * @param banner
     * @return
     */
    @PostMapping(value = "updateType")
    @ResponseBody
    public boolean updatePermission(HttpServletRequest request, MultipartFile banner) {
        GoodsClass goodsClass = new GoodsClass();
        goodsClass.setId(request.getParameter("id"));
        goodsClass.setUpdateTime(LocalDateTime.now());
        goodsClass.setName(request.getParameter("name"));
        goodsClass.setPId(request.getParameter("pid"));
        goodsClass.setType(request.getParameter("type"));
        goodsClass.setTypeDesc(request.getParameter("typeDesc"));
        goodsClass.setTypeStatus(request.getParameter("typeStatus"));
        goodsClass.setTypeSort(request.getParameter("typeSort"));
        if (banner != null) {
            //文档上传oss
            try {
                String fileName = banner.getOriginalFilename();
                String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
                InputStream inputStream = banner.getInputStream();
                Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODSCLASS/");
                goodsClass.setBanner(uploadByInputStream.get("path").toString());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        this.bannerService.updateById(goodsClass);
        return true;
    }

    /**
     * 删除分类
     *
     * @param id
     */
    @DeleteMapping("{id}")
    @ApiOperation(value = "删除分类")
    @ResponseBody
    @PreAuthorize("hasAuthority('goods:type:del')")
    public void delete(@PathVariable String id) {
        this.bannerService.deleteById(id);
    }
}

